<template>
  <el-drawer
      v-model="showFlag"
      append-to-body
      :before-close="cancel">
    <div style="margin: 20px">
      <el-form :model="refForm" :rules="rules" ref="formView" label-position="top" size="default">

        <el-form-item label="图书名称" prop="bookName">
          <el-input v-model="refForm.bookName"/>
        </el-form-item>

        <el-form-item label="作者" prop="bookAuthro">
          <el-input v-model="refForm.bookAuthro"/>
        </el-form-item>
        <el-form-item label="ISBN" prop="bookIsbn">
          <el-input v-model="refForm.bookIsbn"/>
        </el-form-item>
        <el-form-item label="出版社" prop="bookCbs">
          <el-input v-model="refForm.bookCbs"/>
        </el-form-item>
        <el-form-item label="出版时间" prop="bookCbTime">
          <el-input v-model="refForm.bookCbTime"/>
        </el-form-item>
        <el-form-item label="页数" prop="bookPages">
          <el-input v-model="refForm.bookPages"/>
        </el-form-item>
        <el-form-item label="图书封面" prop="bookPic">

          <el-upload class="h100 personal-user-left-upload"
                     :action="uploadUrl" multiple :limit="1"
                     ref="uploadRef"
                     :on-success="onSuccess"
                     :on-error="onError"
                     :before-upload="handlerBefore"
                     :file-list="uploadFileList"
                     :show-file-list="false">
            <img v-if="refForm.bookPic" :src="refForm.bookPic" />
            <el-icon v-if="!refForm.bookPic" class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>


      </el-form>
    </div>
    <template #footer>
      <div style="text-align: center;margin-bottom: 10px">
        <el-button size="default" @click="cancel()">取消</el-button>
        <el-button size="default" type="primary" @click="subimt()" v-auths="['auth-book-add','auth-book-update']">
          提交
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import {ElMessage} from "element-plus";
import {getUploadFileMaxSize} from "/@/api/oss";
import { Plus } from '@element-plus/icons-vue'
import {updateBook,addBook} from "/@/api/auth/book";
const uploadUrl = import.meta.env.VITE_PUBLIC_PATH + '/sysOss/upload'
const showFlag = ref(false)
const formView = ref()
const {proxy} = getCurrentInstance()
const uploadRef = ref()
const fileSize = ref()
const uploadFileList = ref([])
const emits = defineEmits(['ok'])
const rules = reactive({
  bookName: [
    {required: true, message: '请输入图书名称', trigger: 'blur'},
  ],
  bookAuthro: [
    {required: true, message: '请输入作者', trigger: 'blur'},
  ],
  bookIsbn: [
    {required: true, message: '请输入ISBN', trigger: 'blur'},
  ],
  bookCbs: [
    {required: true, message: '请输入出版社', trigger: 'blur'},
  ],
  bookCbTime: [
    {required: true, message: '请输入出版时间', trigger: 'blur'},
  ],
  bookPages: [
    {required: true, message: '请输入页数', trigger: 'blur'},
  ],
})
const refForm = reactive({
  bookId: undefined,
  bookName: undefined,
  bookAuthro: undefined,
  bookIsbn: undefined,
  bookCbs: undefined,
  bookCbTime: undefined,
  bookPic: undefined,
  bookPages: undefined,
})
const open = (node) => {
  if(node){
    refForm.bookId= node.bookId
    refForm.bookName= node.bookName
    refForm.bookAuthro=node.bookAuthro
    refForm.bookIsbn=node.bookIsbn
    refForm.bookCbs=node.bookCbs
    refForm.bookCbTime= node.bookCbTime
    refForm.bookPic= node.bookPic
    refForm.bookPages= node.bookPages
  }
  showFlag.value = true
}
const cancel = () => {
  showFlag.value = false
  proxy.$refs.formView.clearValidate(['bookName','bookAuthro','bookIsbn','bookCbs','bookCbTime','bookPic','bookPages'])
  proxy.$refs.formView.resetFields()
  refForm.bookId= undefined
  refForm.bookName= undefined
  refForm.bookAuthro=undefined
  refForm.bookIsbn=undefined
  refForm.bookCbs=undefined
  refForm.bookCbTime= undefined
  refForm.bookPic= undefined
  refForm.bookPages= undefined
}
const subimt = async () => {
  await formView.value.validate((valid) => {
    if (valid) {
      if (!refForm.bookId) {
        addBook(refForm).then(res => {
          ElMessage.success(res.msg)
          cancel()
          emits('ok')
        })
      } else {
        updateBook(refForm).then(res => {
          ElMessage.success(res.msg)
          cancel()
          emits('ok')
        })
      }
    }
  })
}
defineExpose({
  open,
})
const handlerBefore=(file) => {
  if (checkSize(file)) {
    return true
  } else {
    ElMessage.error("上传文件大小不能超过:" + (fileSize.value / 1024 / 1024) + "MB")
    return false
  }
}
const checkSize = (file) => {
  return file.size < fileSize.value
}
//文件上传成功时的钩子
const onSuccess = async (response, uploadFile, uploadFiles) => {
  let {code} =response
  if(code ===200){
    ElMessage.success("封面上传成功")
    refForm.bookPic=response.data.fileOssUrl
    uploadFileList.value=[]
    uploadRef.value.clearFiles()
  }
}
//文件上传失败时的钩子
const onError = (error, uploadFile, uploadFiles) => {
  ElMessage.error("文件上传失败，请重试")
}
onBeforeMount(()=>{
  getUploadFileMaxSize().then(res => {
    fileSize.value = res.data
  })
})
</script>

<style scoped lang="scss">
.personal-user-left-upload {
  img {
    width: 100%;
    height: 100%;
    border-radius: 3px;
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>